package ca.etsmtl.log730.projet2.connectors.server.tcpip;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import ca.etsmtl.log730.projet2.connectors.AbstractAdapter;
import ca.etsmtl.log730.projet2.connectors.server.ServerSetup;

public class TcpIpServerSetup implements ServerSetup {
	private int port = 1234;
	public int getPort() {
		return port;
	}
	public void setPort(int p) {
		this.port = p;
	}
	private IoAcceptor acceptor = null;
	@Override
	public void open() {
        acceptor = new NioSocketAcceptor();

        acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
        acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        System.out.println("LISTENING ON PORT " + getPort());
        acceptor.setHandler( (IoHandler) getAdapter());
        acceptor.getSessionConfig().setReadBufferSize( 2048 );
        acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
        try {
			acceptor.bind( new InetSocketAddress(port) );
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void close() {
		acceptor.unbind();
	}
	
	private AbstractAdapter adapter;
	@Override
	public void setAdapter(AbstractAdapter aa) {
		adapter = aa;
	}
	@Override
	public AbstractAdapter getAdapter() {
		return adapter;
	}
	
	
}
